package com.yangmin.springcloud.controller;

import com.yangmin.springcloud.entities.CommonResult;
import com.yangmin.springcloud.entities.Payment;
import com.yangmin.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String paymentPort;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/add")
    public CommonResult<Integer> addPayment(@RequestBody Payment payment) {
        Integer integer = paymentService.insertOnePayment(payment);
        if (integer > 0) {
            return new CommonResult<Integer>("200", "插入成功:8001", integer);
        }
        return new CommonResult<Integer>("500", "插入失败哈哈:8001", null);

    }

    @GetMapping("/select/{id}")
    public CommonResult<Payment> selectPayment(@PathVariable("id") Integer id) {
        return new CommonResult<Payment>("200", "查询成功:" + paymentPort, paymentService.searchById(id));
    }

    @GetMapping("/discovery/")
    public DiscoveryClient discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("服务名称：{}", service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t"
                    + instance.getUri());
        }

        return this.discoveryClient;
    }


    @GetMapping("/getPort")
    public CommonResult<String> getPort() {
        return new CommonResult<String>("200", "success", paymentPort);
    }

    // =========zipkin
    @GetMapping("/payment/zipkin")
    public CommonResult<String> paymentZipkin() {
        return new CommonResult<String>("200", "success", "hi ,i'am paymentzipkin server fall back，welcome to atguigu，O(∩_∩)O哈哈~");
    }
}
